<template>
  <div class="container">
    <el-card>
      试题录入
      <el-divider></el-divider>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="学科" prop="subjectID">
          <el-select
            v-model="ruleForm.subjectID"
            placeholder="请选择"
            style="width: 400px"
            @change="editSubject"
          >
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录" prop="catalogID">
          <el-select
            v-model="ruleForm.catalogID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in catalogOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="企业" prop="enterpriseID">
          <el-select
            v-model="ruleForm.enterpriseID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in enterpriseOptions"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 省 -->
        <el-form-item label="城市" prop="city">
          <el-select
            v-model="ruleForm.province"
            placeholder="请选择"
            style="width: 195px"
            @change="editCity"
          >
            <el-option
              v-for="item in cityOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          &nbsp;
          <!-- 市 -->
          <el-select
            v-model="ruleForm.city"
            placeholder="请选择"
            style="width: 195px"
          >
            <el-option
              v-for="item in areaOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向" prop="direction">
          <el-select
            v-model="ruleForm.direction"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in directionOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="题型" prop="questionType">
          <el-radio-group v-model="ruleForm.questionType">
            <el-radio
              :label="item.value + ''"
              v-for="item in questionType"
              :key="item.value"
              @change="changeQuestionType({})"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-radio-group v-model="ruleForm.difficulty">
            <el-radio
              :label="item.value + ''"
              v-for="item in difficulty"
              :key="item.value"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干 -->
        <el-form-item label="题干" prop="question">
          <quill-editor
            v-model="ruleForm.question"
            :options="editorOption1"
            @blur="onEditorBlur"
            style="height: 200px"
            ref="myQuillEditor1"
          >
          </quill-editor>
        </el-form-item>
        <br />
        <br />
        <br />
        <!-- 选项 需要分情况和试题类型关联-->
        <!-- :label="true"?? -->
        <!-- 使用 Radio 组件，只需要设置v-model绑定变量，选中意味着变量的值为相应 Radio label属性的值，label可以是String、Number或Boolean -->
        <el-form-item
          label="选项："
          prop="options"
          v-if="ruleForm.questionType !== '3'"
        >
          <div
            class="option_item"
            v-for="item in ruleForm.options"
            :key="item.code"
          >
            <el-radio
              v-if="ruleForm.questionType === '1'"
              v-model="item.isRight"
              style="margin-bottom: 30px"
              :label="true"
              @change="changeQuestionType(item)"
              >{{ item.code }}：</el-radio
            >
            <el-checkbox
              v-else
              v-model="item.isRight"
              style="margin-bottom: 30px"
              :label="true"
              >{{ item.code }}：</el-checkbox
            >
            <el-input style="width: 240px" v-model="item.title" ></el-input>
            <!-- 上传腾讯云 -->
            <el-upload
              style="margin-left: 4px"
              class="avatar-uploader"

              action="#"
              :show-file-list="false"
              :http-request="
                (obj) => {
                  handleUpload(item, obj)
                }
              "
              :class="{myupload: item.img}"
            >
              <template v-if="item.loading">
                <el-progress
                  class="loading"
                  type="circle"
                  :percentage="item.percentage"
                ></el-progress>
              </template>
              <template v-else>
                <img v-if="item.img" :src="item.img" class="avatar" />
                <span v-else>上传图片</span>
              </template>
              <i class="el-icon-circle-close"></i>
            </el-upload>
          </div>
          <!-- 添加按钮 -->
          <el-button
            :disabled="ruleForm.questionType === '1'"
            type="danger"
            size="small"
            @click="addOption"
            >+增加选项与答案</el-button
          >
        </el-form-item>
        <el-form-item label="解析视频">
          <el-input v-model="ruleForm.videoURL" style="width: 400px"></el-input>
        </el-form-item>
        <!-- 答案解析 -->
        <el-form-item label="答案解析" prop="question">
          <quill-editor
            v-model="ruleForm.answer"
            :options="editorOption2"
            style="height: 200px"
            ref="myQuillEditor2"
          >
          </quill-editor>
        </el-form-item>

         <!-- 上传腾讯云 -->
          <el-upload
            hidden
            action="#"
            :show-file-list="false"
            :http-request="
              (obj) => {
                handleUpload({}, obj)
              }
            "
          >
            <el-button size="small" class="rich-upload" type="primary"
              >点击上传</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        <br />
        <br />
        <br />
        <!--题目备注 -->
        <el-form-item label="题目备注">
          <el-input
            type="textarea"
            v-model="ruleForm.remarks"
            style="width: 400px"
          ></el-input>
        </el-form-item>
        <el-form-item label="试题标签" prop="tags">
          <el-select
            multiple
            filterable
            allow-create
            default-first-option
            v-model="ruleForm.tags"
            placeholder="请选择试题标签"
            style="width: 400px"
          >
            <el-option
              v-for="item in tagsOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 确认提交,没有ID做提交,有ID做回显修改-->
        <el-form-item>
          <el-button v-if="!$route.query.id" @click="submit" type="primary"
            >确认提交</el-button
          >
          <el-button v-else @click="update" type="success">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import hljs from 'highlight.js'
import 'highlight.js/styles/xcode.css'
import { quillEditor } from 'vue-quill-editor'
import { simple } from '@/api/hmmm/subjects.js'
import { list as getCompanyOptions } from '@/api/hmmm/companys'
import {
  provinces as getCityOptions,
  citys as getAreaOptions
} from '@/api/hmmm/citys'
import { simple as getTagOptions } from '@/api/hmmm/tags'
import { add, detail, update } from '@/api/hmmm/questions'
import { simple as catalogOptionList } from '@/api/hmmm/directorys.js'
// 导入常量
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
// 创建腾讯云实例
var cos = new COS({
  SecretId: 'AKIDrnZ8YlNp4B5lJfpmV0GH3asviFZgcJlx',
  SecretKey: '3qPkpeEahdLp31jBPO8dttdHhurYzB7n'
})
// console.log(getCityOptions())
// console.log(questionType)
export default {
  components: {
    quillEditor
  },
  data () {
    const arrayOption = [
      ['bold', 'italic', 'underline', 'strike'],
      [{ list: 'ordered' }, { list: 'bullet' }],
      ['blockquote'],
      ['code-block', 'image', 'link']
    ]
    return {
      ruleForm: {
        subjectID: null, // 学科
        catalogID: null, // 目录
        enterpriseID: null, // 企业简称
        direction: null, // 方向
        questionType: '1', // 试题类型
        difficulty: '1', // 难度
        city: null, // 城市
        province: null, // 省份
        question: null, // 富文本
        // videoURL: null, // 解析视频
        // answer: null, // 答案解析
        // tags: null, // 标签
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ] // 选项
      },
      editorOption1: {
        placeholder: '请输入题干',
        modules: {
          toolbar: {
            container: arrayOption,
            handlers: {
              // 重写图片上传
              image: () => {
                this.myQuillEditor = 'myQuillEditor1'
                document.querySelector('.rich-upload').click()
              }
            }
          },
          syntax: {
            highlight: (text) => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        }
      },
      editorOption2: {
        placeholder: '请输入答案',
        modules: {
          toolbar: {
            container: arrayOption,
            handlers: {
              // 重写图片上传
              image: () => {
                this.myQuillEditor = 'myQuillEditor2'
                document.querySelector('.rich-upload').click()
              }
            }
          },
          syntax: {
            highlight: (text) => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        }
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }]
      },
      // 题型
      questionType,
      // 难度
      difficulty,
      // 题干
      direction,
      // 学科选项
      subjectOptions: [],
      // 目录选项
      catalogOptions: [],
      // 企业选项
      enterpriseOptions: [],
      // 城市选项
      cityOptions: getCityOptions(),
      // 地区选项
      areaOptions: [],
      // 方向选项
      directionOptions: direction,
      // 标签选项
      tagsOptions: []
    }
  },
  created () {
    this.getSimple()
    this.getCompanyList()
    if (this.$route.query.id) {
      this.getQuestion()
    }
  },
  // 监听跳转的过来的ID
  watch: {
    '$route.query': function () {
      if (this.$route.query.id) {
        this.getQuestion()
      } else {
        this.ruleForm = {
          subjectID: null,
          catalogID: null,
          enterpriseID: null,
          province: null,
          city: null,
          direction: null,
          questionType: '1',
          difficulty: '1',
          question: null,
          options: [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }
          ]
        }
        this.$nextTick(() => {
          this.$refs.ruleForm.clearValidate()
        })
      }
    }
  },
  methods: {
    // 富文本上传
    richUploadSuccess (url) {
      if (url) {
        // 获取文本编辑器
        debugger
        console.log(this.myQuillEditor)
        const quill = this.$refs[this.myQuillEditor].quill // 获取光标位置
        const pos = quill.getSelection().index
        // 插入图片到光标位置
        quill.insertEmbed(pos, 'image', 'https://' + url)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        this.$message.error('图片插入失败')
      }
    },
    // 获取题目信息
    async getQuestion () {
      const { data } = await detail({ id: this.$route.query.id })
      data.tags = data.tags?.split(',')
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })

      this.ruleForm = data
      const res = await catalogOptionList({ subjectID: this.ruleForm.subjectID })
      this.catalogOptions = res.data
      const res2 = await getTagOptions({ subjectID: this.ruleForm.subjectID })
      this.tagsOptions = res2.data
      // 滚动顶部
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },

    // obj是上传文件所在的一个配置对象
    // obj是上传文件所在的一个配置对象
    handleUpload (upList, obj) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let timer = null
      if (obj.file) {
        // 执行上传操作
        cos.putObject(
          {
            Bucket: 'jepson-80-1305918422' /* 存储桶 */,
            Region: 'ap-shanghai' /* 存储桶所在地域，必须字段 */,
            Key: obj.file.name /* 文件名 */,
            StorageClass: 'STANDARD', // 上传模式, 标准模式
            Body: obj.file, // 上传文件对象
            // 上传进度
            onProgress: (progressData) => {
              if (progressData.percent === 1) {
                upList.percentage = 100
                upList.loading = false
                clearInterval(timer)
                return
              }
              upList.loading = true
              clearInterval(timer)
              timer = setInterval(function () {
                if (upList.percentage >= 98) return
                upList.percentage++
              }, 50)
            }
          },
          (err, data) => {
            loading.close()
            if (err) {
              clearInterval(timer)
              upList.loading = false
              return console.log(err)
            }
            // 如果是空对象 代表是富文本的图片上传
            if (!upList?.code) {
              this.richUploadSuccess(data.Location)
            }
            upList.img = 'https://' + data.Location
          }
        )
      }
    },

    // 对部分表单字段进行校验的方法
    onEditorBlur () {
      this.$refs.ruleForm.validateField('question')
    },
    // 清空选中的状态
    changeQuestionType (i) {
      this.ruleForm.options.forEach((item) => {
        item.isRight = false
      })
      i.isRight = true
    },
    // 增加选项与答案按钮
    addOption () {
      // 规律：
      // 索引 0 ---> A  ascii  65
      // 索引 1 ---> B  ascii  66
      // 索引 2 ---> C  ascii  67
      // 索引 3 ---> D  ascii  68
      // 索引 4 ---> E  ascii  69
      // ...
      // 总结 code = String.fromCharCode(index + 65)
      this.ruleForm.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.ruleForm.options.length),
        title: '',
        img: ''
      })
    },
    // 基础题库详情
    async getQuestions () {
      console.log(this.$router.this.$route.query.id)
      const res = await detail()
      console.log(res)
    },
    // 修改学科后获取目录
    async editSubject () {
      this.ruleForm.catalogID = null
      // 学科下目录
      const { data } = await catalogOptionList({
        subjectID: this.ruleForm.subjectID
      })
      this.catalogOptions = data
      this.ruleForm.tags = null
      const res = await getTagOptions({ subjectID: this.ruleForm.subjectID })
      this.tagsOptions = res.data
    },
    // 学科简单列表
    async getSimple () {
      const { data } = await simple()
      this.subjectOptions = data
    },
    // 企业列表
    async getCompanyList () {
      const { data } = await getCompanyOptions({ pagesize: 10000 })
      this.enterpriseOptions = data.items
    },
    // 城市
    editCity () {
      this.ruleForm.city = null
      this.areaOptions = getAreaOptions(this.ruleForm.province) // 参数,城市
    },
    // 添加基础题库
    submit () {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          const data = { ...this.ruleForm }
          // tags收集到一个数组中,需要连成字符串
          data.tags = data.tags?.join(',')
          debugger
          // console.log(data.tags)
          const res = await add(data)
          console.log(res)
          this.$message.success('添加成功')
          this.$router.push('/questions/list')
        }
      })
    },
    // 修改题库
    update () {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          const data = { ...this.ruleForm }
          data.tags = data.tags?.join(',')
          await update(data)
          this.$message.success('修改成功')
          this.$router.push('/questions/list')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 20px;
}
::v-deep {
  .el-textarea__inner {
    height: 95px;
  }
}

.quill-editor {
  ::v-deep {
    img {
      width: 100px;
    }
  }
}
::v-deep .ql-editor {
  height: 200px;
}
::v-deep .ql-toolbar.ql-snow {
  padding: 0 8px;
}
.option_item {
  padding-bottom: 20px;
}
.avatar-uploader {
  display: inline-block;
  height: 60px;
  width: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  vertical-align: middle;
  line-height: 60px;
  position: relative;
  ::v-deep.el-upload {
    width: 100px;
  }
  .loading {
    position: absolute;
    width: 80%;
    height: 80%;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    ::v-deep {
      .el-progress-circle {
        width: 50% !important;
        height: 100% !important;
        display: flex;
        align-items: center;
        margin: 0 auto;
      }
    }
  }
}
::v-deep {
  .el-upload {
    cursor: pointer;
    position: relative;
    height: 60px;
  }
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.el-icon-circle-close {
  position: absolute;
  right: -11px;
  top: 0;
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
.avatar {
  width: 100px;
  height: 60px;
  display: block;
  overflow: hidden;
}
.myupload {
  ::v-deep.el-upload--picture-card {
    display: none;
  }
}
</style>
